package com.security.springmvc.service.imlp;

import com.security.springmvc.model.AuthenticationRequest;
import com.security.springmvc.model.UserDto;
import com.security.springmvc.service.AuthenticationService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Override
    public UserDto authenticate(AuthenticationRequest authenticationRequest) {
        if(authenticationRequest == null ||
                authenticationRequest.getUsername() == null ||
                authenticationRequest.getPassword() == null) {
            throw new RuntimeException("账号或密码不能为空");
        }
        UserDto user = getUserDto(authenticationRequest.getUsername());
        if(user == null) throw new RuntimeException("用户不存在");
        if(!authenticationRequest.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }
        return user;
    }

    private UserDto getUserDto(String username) {
        return userMap.get(username);
    }

    public Map<String,UserDto> userMap = new HashMap<>();
    {
        Set<String> authoritiesAdmin = new HashSet<>();
        authoritiesAdmin.add("p1");
        authoritiesAdmin.add("p2");
        Set<String> authoritiesUser = new HashSet<>();
        authoritiesUser.add("p1");

        userMap.put("admin",new UserDto("1","admin","admin","管理员","133223",authoritiesAdmin));
        userMap.put("user",new UserDto("2","user","123456","用户","192343",authoritiesUser));
    }
}
